package com.lj.admin.controller.monitor;

import cn.hutool.core.text.CharSequenceUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lj.common.core.ajax.Result;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 缓存监控
 *
 * @author 小李飞刀
 */
@RestController
@RequestMapping("/monitor/cache")
public class CacheController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取缓存信息
     *
     * @return 结果
     */
    @PreAuthorize("@permission.hasPermission('monitor:cache:list')")
    @GetMapping()
    public Result getInfo() {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::info);
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::dbSize);

        Map<String, Object> result = Maps.newHashMap();
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = Lists.newArrayList();
        assert commandStats != null;
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = Maps.newHashMap();
            String property = commandStats.getProperty(key);
            data.put("name", CharSequenceUtil.removeSuffix(key, "cmdstat_"));
            data.put("value", CharSequenceUtil.subBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);
        return Result.success(result);
    }
}
